package pet_sql

import (
	"gorm.io/gorm"
	"my-systems/pet-system/internal/db"
	"my-systems/pet-system/internal/models"
)

func GetALlUserPet(uid int) ([]models.Pet, error) {
	var pets []models.Pet
	err := db.DB.Model(&models.Pet{}).Where("user_id = ?", uid).Find(&pets).Error
	return pets, err
}

func AddPets(pet *models.Pet) error {
	err := db.DB.Model(&models.Pet{}).Create(pet).Error
	return err
}

func GetByIDPet(pid uint, uid int) (pet *models.Pet, err error) {
	err = db.DB.Model(&models.Pet{}).Where("id = ? and user_id=?", pid, uid).First(&pet).Error
	return pet, err
}

func UpPetAvatar(pid int, uid int, pet *models.Pet) error {
	return db.DB.Model(&models.Pet{}).Where("id = ? and user_id=?", pid, uid).Updates(&pet).Error
}

func AddPetPhoto(pet *models.Pet, avatar string) error {
	return db.DB.Model(&models.PetPhotos{}).Create(&models.PetPhotos{
		PetID: int64(pet.ID),
		URL:   avatar,
	}).Error
}

func ExistOrNotByID(pid uint, uid int) (pet *models.Pet, exist bool, err error) {
	err = db.DB.Model(&models.Pet{}).Where("id = ? and user_id=?", pid, uid).First(&pet).Error
	if err != nil {
		return nil, false, err
	}
	return pet, true, nil
}

func UpdatePet(tx *gorm.DB, pid uint, uid int, pet *models.Pet) error {
	if tx == nil {
		tx = db.DB
	}
	return tx.Model(&models.Pet{}).Where("id = ? and user_id=?", pid, uid).Updates(&pet).Error
}

func DeletePet(tx *gorm.DB, pid uint, uid int) error {
	if tx == nil {
		tx = db.DB
	}
	return tx.Model(&models.Pet{}).Where("id = ? and user_id=?", pid, uid).Delete(&models.Pet{}).Error
}

func DeletePetPhoto(pid uint) error {
	return db.DB.Model(&models.PetPhotos{}).Where("pet_id = ?", pid).Delete(&models.PetPhotos{}).Error
}

func GetSalePets(available bool) ([]models.PetsAreAvailableForSale, error) {
	var pets []models.PetsAreAvailableForSale
	var err error
	//fmt.Println(available)
	if available { // 查看可售
		err = db.DB.Model(&models.PetsAreAvailableForSale{}).Where("is_available = ?", available).Find(&pets).Error
	} else { // 查看所有
		err = db.DB.Model(&models.PetsAreAvailableForSale{}).Find(&pets).Error
	}

	return pets, err
}

func GetSalePetByID(pid string) (pet *models.PetsAreAvailableForSale, err error) {
	err = db.DB.Model(&models.PetsAreAvailableForSale{}).Where("id = ?", pid).First(&pet).Error
	return pet, err
}
